<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="编译之后的 Java 方法以字节码的形式存储在 class 文件中。前面已经初步实现了 Java 虚拟机栈、帧、操作数栈和局部变量表等运行时数据区。那么 JVM 是如何操作局部变量表和操作数栈中的数据呢？这就涉及到了 JVM 的字节码指令集。这一节对 JVM 的字节码指令集做一个介绍，本节所实现的指令位于项目的 instructions 包下。  字节码简介字节码是运行在虚拟机上的机器码,每一个">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(9)-指令集">
<meta property="og:url" content="https://zachaxy.github.io/2017/05/13/手写JVM系列-9-指令集/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="编译之后的 Java 方法以字节码的形式存储在 class 文件中。前面已经初步实现了 Java 虚拟机栈、帧、操作数栈和局部变量表等运行时数据区。那么 JVM 是如何操作局部变量表和操作数栈中的数据呢？这就涉及到了 JVM 的字节码指令集。这一节对 JVM 的字节码指令集做一个介绍，本节所实现的指令位于项目的 instructions 包下。  字节码简介字节码是运行在虚拟机上的机器码,每一个">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.306Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(9)-指令集">
<meta name="twitter:description" content="编译之后的 Java 方法以字节码的形式存储在 class 文件中。前面已经初步实现了 Java 虚拟机栈、帧、操作数栈和局部变量表等运行时数据区。那么 JVM 是如何操作局部变量表和操作数栈中的数据呢？这就涉及到了 JVM 的字节码指令集。这一节对 JVM 的字节码指令集做一个介绍，本节所实现的指令位于项目的 instructions 包下。  字节码简介字节码是运行在虚拟机上的机器码,每一个">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/05/13/手写JVM系列-9-指令集/">





  <title>手写JVM系列(9)-指令集 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/13/手写JVM系列-9-指令集/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(9)-指令集</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-13T23:03:42+08:00">
                2017-05-13
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,199
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <blockquote>
<p>编译之后的 Java 方法以字节码的形式存储在 class 文件中。前面已经初步实现了 Java 虚拟机栈、帧、操作数栈和局部变量表等运行时数据区。那么 JVM 是如何操作局部变量表和操作数栈中的数据呢？这就涉及到了 JVM 的字节码指令集。这一节对 JVM 的字节码指令集做一个介绍，本节所实现的指令位于<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目</a>的 instructions 包下。</p>
</blockquote>
<h1 id="字节码简介"><a href="#字节码简介" class="headerlink" title="字节码简介"></a>字节码简介</h1><p>字节码是运行在虚拟机上的机器码,每一个类或者接口都会被 Java 编译器编译成一个 class 文件，类或接口的方法信息就放在 class 文件的 method_info 结构中。如果方法不是抽象的，也不是本地方法，方法的 Java 代码就会被编译器编译成字节码（即使方法是空的，编译器也会生成一条 return 语句），存放在 method_info 结构的<strong>Code 属性</strong>中。 ==&gt; 字节码一般来说是针对方法中的步骤的；</p>
<h1 id="指令简介"><a href="#指令简介" class="headerlink" title="指令简介"></a>指令简介</h1><p>字节码中存放编码后的 Java 虚拟机指令。</p>
<p><strong>指令 = 操作码 + 操作数（如果有的话）</strong></p>
<ul>
<li>操作码（Opcode）：一个字节长度，代表着某种特定操作含义。</li>
<li>操作数（Operands）：操作码后面需要跟零到多个代表该操作码所需的参数。</li>
</ul>
<p>所以 Java 虚拟机使用的是<strong>变长指令</strong></p>
<p>如果把指令想象成函数的话，操作数就是它的参数。每条指令都以一个单字节的操作码（opcode）开头。由于只使用一字节表示操作码，显而易见，Java 虚拟机最多只能支持 256（2^8 ）条指令。</p>
<p>Java 虚拟机规范已经定义了 205 条指令，操作码分别是 0（0x00）到 202（0xCA）、254（0xFE）和 255（0xFF）。这 205 条指令构成了 Java 虚拟机的指令集（instruction set）。</p>
<p>字节码指令是一种具有鲜明特点，优劣势都很突出的指令集架构。</p>
<p>缺点：由于 Class 文件格式放弃了将编译后操作数长度对齐，那么如果处理那些超过一个字节的数据时，不得不在运行时从字节中重建出具体数据，eg：将一个 16 位无符号整数用两字节（byte1，byte2）存储起来，那么在读取该 16 位整数时，需要这样转换：<code>( byte1 &lt;&lt; 8 ) | byte2</code>，这导致解释执行操作码时损失了一些性能。</p>
<p>优点：放弃了操作数长度对其，意味着可以省略很多填充和间隔符号，尽可能获取短小精干的编译代码（小数据量，高效传输）</p>
<h1 id="操作码的数据类型"><a href="#操作码的数据类型" class="headerlink" title="操作码的数据类型"></a>操作码的数据类型</h1><p>为了让编码后的字节码更加紧凑，很多操作码本身就隐含了操作数，比如把常数 0 推入操作数栈的指令是 iconst_0。</p>
<p><strong>操作数栈</strong>和<strong>局部变量表</strong>只存放数据的值，并不记录数据类型。结果就是：<strong>指令必须知道自己在操作什么类型的数据。</strong>这一点也直接反映在了操作码的助记符上。</p>
<p>例如：</p>
<p>iadd 指令就是对 int 值进行加法操作；</p>
<p>dstore 指令把操作数栈顶的 double 值弹出，存储到局部变量表中；</p>
<p>areturn 从方法中返回引用值。</p>
<p>也就是说，如果某类指令可以操作不同类型的变量，则助记符的<strong>第一个字母表示变量类型</strong>。</p>
<table>
<thead>
<tr>
<th>助记符首字母</th>
<th>数据类型</th>
<th>例子</th>
</tr>
</thead>
<tbody><tr>
<td>a</td>
<td>reference</td>
<td>aload、astore、areturn</td>
</tr>
<tr>
<td>b</td>
<td>byte/boolean</td>
<td>bipush、baload</td>
</tr>
<tr>
<td>c</td>
<td>char</td>
<td>caload、castore</td>
</tr>
<tr>
<td>d</td>
<td>double</td>
<td>dload、dstore、dadd</td>
</tr>
<tr>
<td>f</td>
<td>float</td>
<td>fload、fstore、fadd</td>
</tr>
<tr>
<td>i</td>
<td>int</td>
<td>iload、istore、iadd</td>
</tr>
<tr>
<td>l</td>
<td>long</td>
<td>lload、lstore、ladd</td>
</tr>
<tr>
<td>s</td>
<td>short</td>
<td>sipush、sastore</td>
</tr>
</tbody></table>
<p>并非每个基本数据类型都有对应的操作码，从上图可以看到大部指令都没有直接支持 byte、char、short、boolean，编译器会在编译器或者运行期将 byte 和 short 类型的数据<strong>带符号扩展</strong>为相应的 int 类型，将 boolean 和 char 类型数据<strong>零位扩展</strong>为相应的 int 类型。因此，大多数对于 byte、char、short、boolean 的操作，实际上都是使用相应的 int 类型作为运算类型。</p>
<h1 id="指令的分类"><a href="#指令的分类" class="headerlink" title="指令的分类"></a>指令的分类</h1><p>因为使用一字节表示操作码，所以 Java 虚拟机最多只能支持 256（2^8 ）条指令。</p>
<p>Java 虚拟机规范已经定义了 205 条指令，操作码分别是 0（0x00）到 202（0xCA）、254（0xFE）和 255（0xFF）。这 205 条指令构成了 Java 虚拟机的指令集（instruction set）。</p>
<p>Java 虚拟机规范把已经定义的 205 条指令按用途分成了 11 类：</p>
<ol>
<li>常量（constants）指令</li>
<li>加载（loads）指令</li>
<li>存储（stores）指令</li>
<li>操作数栈（stack）指令</li>
<li>数学（math）指令</li>
<li>转换（conversions）指令</li>
<li>比较（comparisons）指令</li>
<li>控制（control）指令</li>
<li>引用（references）指令</li>
<li>扩展（extended）指令</li>
<li>保留（reserved）指令</li>
</ol>
<p>注:保留指令共有 3 条。其中一条是留给调试器的，用于实现断点，操作码是<code>202（0xCA）</code>，助记符是<code>breakpoint</code>。另外两条留给<code>Java</code>虚拟机实现内使用，操作码分别是<code>254（0xFE）</code>和<code>266（0xFF）</code>，助记符是<code>impdep1</code>和<code>impdep2</code>。这三条指令不允许出现在 class 文件中。</p>
<p>接下来这上述的 11 类指令做一个简单的介绍，并在每种类别的指令中跳出几个有代表性的进行简要说明。</p>
<h1 id="常量指令"><a href="#常量指令" class="headerlink" title="常量指令"></a>常量指令</h1><p>常量指令把常量<strong>推入操作数栈顶</strong>。常量可以来自三个地方：隐含在操作码里、操作数和运行时常量池。</p>
<h2 id="nop-指令"><a href="#nop-指令" class="headerlink" title="nop 指令"></a>nop 指令</h2><p>nop 指令是最简单的一条指令，因为它什么也不做。</p>
<h2 id="const-系列指令"><a href="#const-系列指令" class="headerlink" title="const 系列指令"></a>const 系列指令</h2><p>这一系列指令把隐含在操作码中的常量值<strong>推入操作数栈顶</strong>。几个具体的例子如下：</p>
<ul>
<li><p>aconst_null 指令把 null 引用推入操作数栈顶</p>
</li>
<li><p>dconst_0 指令把 double 型 0 推入操作数栈顶</p>
</li>
<li><p>iconst_m1 指令把 int 型 -1 推入操作数栈顶</p>
<p>​</p>
</li>
</ul>
<h2 id="bipush-和-sipush-指令"><a href="#bipush-和-sipush-指令" class="headerlink" title="bipush 和 sipush 指令"></a>bipush 和 sipush 指令</h2><p>bipush 指令从<strong>操作数</strong>中获取一个 byte 型整数，扩展成 int 型，然后<strong>推入栈顶</strong>。</p>
<p>sipush 指令从<strong>操作数</strong>中获取一个 short 型整数，扩展成 int 型，然后<strong>推入栈顶</strong>。</p>
<h1 id="加载指令"><a href="#加载指令" class="headerlink" title="加载指令"></a>加载指令</h1><p>加载指令从局部变量表获取变量，然后推入操作数栈顶。加载指令共 33 条，按照所操作变量的类型可以分为 6 类:</p>
<ol>
<li>aload 系列指令操作引用类型变量</li>
<li>dload 系列操作 double 类型变量</li>
<li>fload 系列操作 float 变量</li>
<li>iload 系列操作 int 变量</li>
<li>lload 系列操作 long 变量</li>
<li>xaload 操作数组</li>
</ol>
<h1 id="存储指令"><a href="#存储指令" class="headerlink" title="存储指令"></a>存储指令</h1><p>和加载指令刚好相反，存储指令把变量从操作数栈顶弹出，然后存入局部变量表。</p>
<h1 id="栈指令"><a href="#栈指令" class="headerlink" title="栈指令"></a>栈指令</h1><p>直接对<strong>操作数栈</strong>进行操作，栈指令并不关心变量类型（但是可以确定不是 long 和 double，因为这两种类型占用两个 Slot，所以这里虽然不管类型，但是可以确定是占用了一个 Slot）。共 9 条：</p>
<ul>
<li>pop 和 pop2 指令将栈顶变量弹出</li>
<li>dup 系列指令复制栈顶变量</li>
<li>swap 指令交换栈顶的两个变量</li>
</ul>
<h1 id="数学指令"><a href="#数学指令" class="headerlink" title="数学指令"></a>数学指令</h1><p>数学指令大致对应 Java 语言中的加、减、乘、除等数学运算符。</p>
<p>数学指令共 37 条，包括：</p>
<ul>
<li>算术指令</li>
<li>位移指令</li>
<li>布尔运算指令</li>
<li>自增指令(eg:i++)</li>
</ul>
<h2 id="算术指令"><a href="#算术指令" class="headerlink" title="算术指令"></a>算术指令</h2><ol>
<li>加法（add）指令</li>
<li>减法（sub）指令</li>
<li>乘法（mul）指令</li>
<li>除法（div）指令</li>
<li>求余（rem）指令</li>
<li>取反（neg）指令</li>
</ol>
<h2 id="位移指令"><a href="#位移指令" class="headerlink" title="位移指令"></a>位移指令</h2><ol>
<li><p>左移</p>
</li>
<li><p>右移</p>
<ol>
<li>算术右移（有符号右移）</li>
<li>逻辑右移（无符号右移）</li>
</ol>
<p>​</p>
</li>
</ol>
<h2 id="布尔运算指令"><a href="#布尔运算指令" class="headerlink" title="布尔运算指令"></a>布尔运算指令</h2><p>布尔运算指令只能操作 int 和 long 变量：</p>
<ol>
<li>按位与（and）</li>
<li>按位或（or）</li>
<li>按位异或（xor）</li>
</ol>
<h2 id="iinc-指令"><a href="#iinc-指令" class="headerlink" title="iinc 指令"></a>iinc 指令</h2><p>iinc 指令给局部变量表中的 int 变量增加常量值，局部变量表索引和常量值都由指令的操作数提供。</p>
<h1 id="类型转换指令"><a href="#类型转换指令" class="headerlink" title="类型转换指令"></a>类型转换指令</h1><p>类型转换指令可以分为 4 种：</p>
<ul>
<li>i2x 系列指令把 int 变量强制转换成其他类型</li>
<li>l2x 系列指令把 long 变量强制转换成其他类型</li>
<li>f2x 系列指令把 float 变量强制转换成其他型</li>
<li>d2x 系列指令把 double 变量强制转换成其他类型</li>
</ul>
<p>注意:引用类型转换对应的是 checkcast 指令,在后面的章节会出现。</p>
<h1 id="比较指令"><a href="#比较指令" class="headerlink" title="比较指令"></a>比较指令</h1><p>比较指令可以分为两类：</p>
<ul>
<li>将比较结果推入操作数栈顶。</li>
<li>根据比较结果跳转。</li>
</ul>
<h2 id="lcmp-指令"><a href="#lcmp-指令" class="headerlink" title="lcmp 指令"></a>lcmp 指令</h2><p>用于比较 long 变量,把栈顶的两个 long 变量弹出，进行比较，然后把比较结果（int 型 0、1 或 -1）推入栈顶。</p>
<h2 id="fcmp-指令"><a href="#fcmp-指令" class="headerlink" title="fcmp 指令"></a>fcmp 指令</h2><p>指令和 lcmp 指令很像，但是除了比较的变量类型不同以外，还有一个重要的区别:由于浮点数计算有可能产生 NaN（Not a Number）值，所以比较两个浮点数时，除了大于、等于、小于之外， 还有第 4 种结果：<strong>无法比较</strong></p>
<p>fcmpg 和 fcmpl 指令的区别就在于对第 4 种结果的定义;<br>当两个 float 变量中至少有一个是 NaN 时，用 fcmpg 指令比较的结果是 1，而用 fcmpl 指令比较的结果是 -1。</p>
<h2 id="dcmp-指令"><a href="#dcmp-指令" class="headerlink" title="dcmp 指令"></a>dcmp 指令</h2><p>dcmpg 和 dcmpl 指令用来比较 double 变量,这条指令和 fcmp 指令只是比较的变量类型不同。</p>
<h2 id="if-lt-cond-gt-指令"><a href="#if-lt-cond-gt-指令" class="headerlink" title="if&lt;cond&gt;指令"></a><code>if&lt;cond&gt;</code>指令</h2><p><code>if&lt;cond&gt;</code>指令把操作数栈顶的 int 变量弹出，然后跟 0 进行比较，满足条件则跳转。假设从栈顶弹出的变量是 x，则指令执行跳转操作的条件如下：具体判定之后如何跳转,现在先不讨论;</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ifeq：x==0</span><br><span class="line">ifne：x！=0</span><br><span class="line">iflt：x&lt;0</span><br><span class="line">ifle：x&lt;=0</span><br><span class="line">ifgt：x&gt;0</span><br><span class="line">ifge：x&gt;=0</span><br></pre></td></tr></table></figure>

<h2 id="if-icmp-lt-cond-gt-指令"><a href="#if-icmp-lt-cond-gt-指令" class="headerlink" title="if_icmp&lt;cond&gt;指令"></a><code>if_icmp&lt;cond&gt;指令</code></h2><p><code>if_icmp&lt;cond&gt;</code>指令把栈顶的两个 int 变量弹出，然后进行比较，满足条件则跳转。跳转条件和 if<cond>指令类似。</cond></p>
<h2 id="if-acmp-lt-cond-gt-指令"><a href="#if-acmp-lt-cond-gt-指令" class="headerlink" title="if_acmp&lt;cond&gt;指令"></a><code>if_acmp&lt;cond&gt;指令</code></h2><p>把栈顶的两个引用弹出，根据引用是否相同进行跳转。</p>
<h1 id="控制指令"><a href="#控制指令" class="headerlink" title="控制指令"></a>控制指令</h1><p>分类:</p>
<ul>
<li>goto</li>
</ul>
<ul>
<li>tableswitch</li>
</ul>
<ul>
<li>lookupswitch</li>
</ul>
<h2 id="goto"><a href="#goto" class="headerlink" title="goto"></a>goto</h2><p>goto 指令进行无条件跳转,其操作码后是一个 int16 类型的操作数，所以需要读两个字节并转成成 int16 类型，该操作数即偏移 offset，那么接下来要执行的指令的位置为：<code>pc + offset</code></p>
<h2 id="tableswitch"><a href="#tableswitch" class="headerlink" title="tableswitch"></a>tableswitch</h2><p>Java 语言中的 switch-case 语句有两种实现方式：如果 case 值可以编码成一个索引表(索引值是连续的)，则实现成 tableswitch 指令；否则实现成 lookupswitch 指令</p>
<p>下面这个 Java 方法中的 switch-case 可以编译成 tableswitch 指令，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">chooseNear</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line"><span class="keyword">switch</span> (i) &#123;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">0</span>: <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">1</span>: <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">2</span>: <span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line">  <span class="keyword">default</span>: <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>tableswitch 后跟的操作数是对应 case 分支的跳转 offset，其格式类似于：</p>
<p>default 分支对应的跳转 defaultOffset，0 分支对应的索引 low(这里就是 0)，2 分支对应的索引 high(这里就是 2)，因为 0<del>2 分支对应的跳转是连续的，所以接下来分别对应 0</del>2 分支的跳转 offset。</p>
<p>这里用一个数组存放最合适不过了，数组大小就是<code>high-low+1</code>，这里拿到一个分支跳转的 case 的索引 index，先判断 index 在不在 low 和 high 之间，如果不在，其 offset 就是 defaultOffset，否则就用从数组中找 <code>arr[index-low]</code>，拿到对应的 offset。</p>
<h2 id="lookupswitch"><a href="#lookupswitch" class="headerlink" title="lookupswitch"></a>lookupswitch</h2><p>(索引值是非连续的)下面这个 Java 方法中的 switch-case 则需要编译成 lookupswitch 指令：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">chooseFar</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">switch</span> (i) &#123;</span><br><span class="line">  <span class="keyword">case</span> -<span class="number">100</span>: <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">0</span>: <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="number">100</span>: <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">default</span>: <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为这里的 case 语句并不是连续的，所以不能用数组来表示了，只能是一个 case 的索引，接下来该 case 对应的跳转。</p>
<h1 id="扩展指令"><a href="#扩展指令" class="headerlink" title="扩展指令"></a>扩展指令</h1><h2 id="wide-指令"><a href="#wide-指令" class="headerlink" title="wide 指令"></a>wide 指令</h2><p>加载类指令、存储类指令、ret 指令和 iinc 指令需要按索引访问局部变量表，索引以 uint8 的形式存在字节码中。对于大部分方法来说，<strong>局部变量表大小一般都不会超过 256</strong>，所以用一字节来表示索引就够了。</p>
<p>但是如果有方法的局部变量表超过这限制时,Java 虚拟机规范定义了 wide 指令来扩展前述指令。</p>
<p>wide 指令改变其他指令的行为，modifiedInstruction 字段存放被改变的指令。</p>
<h2 id="ifnull-ifnonnull-指令"><a href="#ifnull-ifnonnull-指令" class="headerlink" title="ifnull/ifnonnull 指令"></a>ifnull/ifnonnull 指令</h2><p>根据引用是否是 null 进行跳转，ifnull 和 ifnonnull 指令把栈顶的引用弹出。</p>
<h2 id="goto-w-指令"><a href="#goto-w-指令" class="headerlink" title="goto_w 指令"></a>goto_w 指令</h2><p>goto_w 指令和 goto 指令的唯一区别就是索引从 2 字节变成了 4 字节。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/05/13/手写JVM系列-9-指令集/" title="手写JVM系列(9)-指令集">https://zachaxy.github.io/2017/05/13/手写JVM系列-9-指令集/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/12/手写JVM系列-8-线程私有的运行时数据/" rel="next" title="手写JVM系列(8)-运行时数据">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(8)-运行时数据
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/05/13/setContentView内部原理/" rel="prev" title="setContentView内部原理">
                setContentView内部原理 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#字节码简介"><span class="nav-number">1.</span> <span class="nav-text">字节码简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#指令简介"><span class="nav-number">2.</span> <span class="nav-text">指令简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#操作码的数据类型"><span class="nav-number">3.</span> <span class="nav-text">操作码的数据类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#指令的分类"><span class="nav-number">4.</span> <span class="nav-text">指令的分类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常量指令"><span class="nav-number">5.</span> <span class="nav-text">常量指令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#nop-指令"><span class="nav-number">5.1.</span> <span class="nav-text">nop 指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#const-系列指令"><span class="nav-number">5.2.</span> <span class="nav-text">const 系列指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#bipush-和-sipush-指令"><span class="nav-number">5.3.</span> <span class="nav-text">bipush 和 sipush 指令</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#加载指令"><span class="nav-number">6.</span> <span class="nav-text">加载指令</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#存储指令"><span class="nav-number">7.</span> <span class="nav-text">存储指令</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#栈指令"><span class="nav-number">8.</span> <span class="nav-text">栈指令</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数学指令"><span class="nav-number">9.</span> <span class="nav-text">数学指令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#算术指令"><span class="nav-number">9.1.</span> <span class="nav-text">算术指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#位移指令"><span class="nav-number">9.2.</span> <span class="nav-text">位移指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#布尔运算指令"><span class="nav-number">9.3.</span> <span class="nav-text">布尔运算指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#iinc-指令"><span class="nav-number">9.4.</span> <span class="nav-text">iinc 指令</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#类型转换指令"><span class="nav-number">10.</span> <span class="nav-text">类型转换指令</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#比较指令"><span class="nav-number">11.</span> <span class="nav-text">比较指令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#lcmp-指令"><span class="nav-number">11.1.</span> <span class="nav-text">lcmp 指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#fcmp-指令"><span class="nav-number">11.2.</span> <span class="nav-text">fcmp 指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#dcmp-指令"><span class="nav-number">11.3.</span> <span class="nav-text">dcmp 指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#if-lt-cond-gt-指令"><span class="nav-number">11.4.</span> <span class="nav-text">if&lt;cond&gt;指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#if-icmp-lt-cond-gt-指令"><span class="nav-number">11.5.</span> <span class="nav-text">if_icmp&lt;cond&gt;指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#if-acmp-lt-cond-gt-指令"><span class="nav-number">11.6.</span> <span class="nav-text">if_acmp&lt;cond&gt;指令</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#控制指令"><span class="nav-number">12.</span> <span class="nav-text">控制指令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#goto"><span class="nav-number">12.1.</span> <span class="nav-text">goto</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#tableswitch"><span class="nav-number">12.2.</span> <span class="nav-text">tableswitch</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lookupswitch"><span class="nav-number">12.3.</span> <span class="nav-text">lookupswitch</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#扩展指令"><span class="nav-number">13.</span> <span class="nav-text">扩展指令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#wide-指令"><span class="nav-number">13.1.</span> <span class="nav-text">wide 指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ifnull-ifnonnull-指令"><span class="nav-number">13.2.</span> <span class="nav-text">ifnull/ifnonnull 指令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#goto-w-指令"><span class="nav-number">13.3.</span> <span class="nav-text">goto_w 指令</span></a></li></ol></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
